package br.com.dev.tcc.database.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import br.com.dev.tcc.bean.Corretor;
import br.com.dev.tcc.database.DatabaseHelper;

public class CorretorDAO {

	private DatabaseHelper databaseHelper;

	public CorretorDAO(DatabaseHelper databaseHelper) {

		this.databaseHelper = databaseHelper;
	}

	public List<Corretor> lista() {

		List<Corretor> lista = new ArrayList<Corretor>();

		SQLiteDatabase db = databaseHelper.getReadableDatabase();
		Cursor cursor = db.rawQuery(
				"SELECT * FROM corretor as c ORDER BY c.nome", null);

		for (int i = 0; i < cursor.getCount(); i++) {

			cursor.moveToNext();

			Corretor corretor = new Corretor();
			corretor.setId(cursor.getInt(0));
			corretor.setName(cursor.getString(1));
			corretor.setEmail(cursor.getString(2));

			lista.add(corretor);
		}

		cursor.close();

		for (Corretor c : lista) {

			cursor = db.rawQuery("select * from corretor_telefone "
					+ "where id_corretor = " + c.getId(), null);

			for (int i = 0; i < cursor.getCount(); i++) {

				cursor.moveToNext();

				String fone = cursor.getString(1);

				c.addPhone(fone);
			}

			cursor.close();
		}
		
		db.close();

		return lista;
	}

	public int salva(Corretor corretor) {

		ContentValues values = new ContentValues();
		values.put("nome", corretor.getName());
		values.put("email", corretor.getEmail());

		SQLiteDatabase database = databaseHelper.getWritableDatabase();

		long resultado = database.insert("corretor", null, values);
		database.close();

		if (resultado == -1) // erro ao tentar inserir corretor
			return -1;

		int id = getLastId();

		List<String> telefones = corretor.getPhones();
		
		if(telefones != null && telefones.size() > 0){
			
			database = databaseHelper.getWritableDatabase();
			
			for (String telefone : corretor.getPhones()) {

				values = new ContentValues();
				values.put("id_corretor", id);
				values.put("telefone", telefone);

				resultado = database.insert("corretor_telefone", null, values);
			}
			
			database.close();
		}
		
		return id;
	}

	private int getLastId() {

		SQLiteDatabase db = databaseHelper.getReadableDatabase();

		Cursor cursor = db.rawQuery("SELECT MAX(id) as id FROM corretor", null);

		int lastId = -1;

		if (cursor.moveToFirst())
			lastId = cursor.getInt(0);

		cursor.close();

		db.close();
		
		return lastId;
	}

	public long remover(int id) {

		SQLiteDatabase database = databaseHelper.getWritableDatabase();

		long resultado = database.delete("corretor", "id=?",
				new String[] { Integer.toString(id) });

		database.close();
		
		return resultado;
	}
}
